package com.yft.util;

import java.beans.Beans;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
//import org.apache.commons.lang.StringUtils;


public class MapUtils {


	/**
	 * clear the map, remove null or empty element 
	 * @param map the map
	 * @return cleared map
	 */	
	@SuppressWarnings("unchecked")
	public static Map clearMap(Map map){
		
		if (map==null || map.isEmpty()) return map;
		
		ArrayList nullKey = new ArrayList();
		Map newMap = map;
		
		Enumeration keys = Collections.enumeration(map.keySet());
		
		while(keys.hasMoreElements()){
			
			Object key = keys.nextElement();
			Object value = newMap.get(key);
			
			

			
			if (value == null)
			nullKey.add(key);

//			if (value instanceof String){
//				if (StringUtils.isBlank((String)value))
//				nullKey.add(key);
//			}
		}
		
		
		for (int i=0; i<nullKey.size(); i++){
			newMap.remove(nullKey.get(i));
		}
		
		return newMap;
		
	}
	
	
	/**
	 * parse the object to map 
	 * @param obj the object
	 * @return the map
	 * 
	 * @throws Exception throw any error 
	 */
	@SuppressWarnings("unchecked")
	public static Map createMap(Object obj) throws Exception{
		
		Map map = null;
		HashMap newMap = new HashMap();
		
		if (Beans.isInstanceOf(obj,Map.class))
		map = (Map) obj;	
		else {
			map = BeanUtils.describe(obj);
			Enumeration keys = Collections.enumeration(map.keySet());
			while(keys.hasMoreElements()){
				
				String key = (String)keys.nextElement();
				Object value = PropertyUtils.getProperty(obj,key);
				
				if (value==null) continue;
				
				if (value instanceof String){
					if (StringUtils.trimToNull((String)value)==null) continue;
				}
				
				newMap.put(key,value);
				
			}
		}
		
		return newMap;
		
	}
	
	
	

}
